<template>
  <div class="upload-page" ref="form">
    <img class="upload-bg" @load="handleLoad" src="/bg1.png">
    <div class="uploader-wrap">
      <label :class="['uploader-label', {'has-photo': photo}]" for="photo" :style="{backgroundImage: photo ? `url(${photo})` : ''}">
      </label>
      <input class="uploader-input" type="file" id="photo" accept="image/*" @change="fileChange" ref="uploaderInput"/>
    </div>
    <div @click="submit" class="submit-wrap"></div>
    <div class="toast" v-show="showToast">{{toastText}}</div>
    <t-dialog v-show="visible" enter-text="返回选择" @enter="handleEnter">{{dialogText}}</t-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { zipImage } from '@/utils/common'
import lrz from 'lrz'

let clicked = false
let ziping = false

export default {
  name: 'uploadPage',
  data () {
    return {
      showToast: false,
      toastTimer: null,
      toastText: '请上传照片',
      dialogText: '',
      visible: false,
      index: 0
    }
  },
  computed: {
    ...mapGetters([
      'photo', 'faceId'
    ])
  },
  components: {
    't-dialog': require('../components/Dialog.vue').default
  },
  created () {
    window._hmt.push(['_trackEvent', '上传页', 'view', '进入上传页'])
    // 从其他页面会到首页时，会清除之前的记录
    this.clearResult()
    this.clearFaceId()
    this.setPhoto('')
    // loading页面第一个显示的图标，用来预加载
    this.index = Math.floor(Math.random() * 17)
  },
  mounted () {
    this.$refs.uploaderInput.value = ''
  },
  methods: {
    ...mapActions(['setPhoto', 'clearResult', 'clearFaceId', 'setFaceId', 'uploadFace']),
    handleLoad (index) {
      // 预加载图片
      new Image().src = require(`@/assets/schools/${this.index}.png`)
      new Image().src = require('@/assets/image/loadingBg.png')
      new Image().src = require('../assets/image/loadingText.png')
      new Image().src = require('../assets/image/pic-bg.png')
    },
    async fileChange (evt) {
      const file = evt.target.files[0]
      ziping = true
      const rst = await lrz(file)
      this.setPhoto(await zipImage(rst.base64))
      ziping = false
      this.$refs.uploaderInput.value = ''
      try {
        await this.uploadFace(this.photo)
        // 用户点击时结果还没出来，则会在结果出来后，延迟做出反应
      } catch (error) {
        if (error.message === '1001' || (error.message + '').charAt(0) === '5') {
          window._hmt.push(['_trackEvent', '上传页', 'dialog', '出现服务器故障提示'])
          this.dialogText = '小猿出现故障惹，等会儿嗷'
        } else if (error.message === '1002') {
          window._hmt.push(['_trackEvent', '上传页', 'dialog', '出现非人脸弹窗提示'])
          this.dialogText = '找不到脸部，请重新挑选一张照片吧！'
        } else {
          window._hmt.push(['_trackEvent', '上传页', 'dialog', '出现网络罢工提示'])
          this.dialogText = '天啦噜，你的网络罢工了，请检查网络'
        }
      } finally {
        if (clicked) {
          this.submit()
          clicked = false
        }
      }
    },
    handleEnter () {
      this.$refs.uploaderInput.value = ''
      this.setPhoto('')
      this.visible = false
      this.dialogText = ''
    },
    toast (msg) {
      // 如果没有上传图片，则toast提示
      this.toastText = msg
      if (this.toastTimer) {
        clearTimeout(this.toastTimer)
      }
      this.showToast = true
      this.toastTimer = setTimeout(() => {
        this.showToast = false
      }, 2000)
    },
    submit () {
      if (!clicked) window._hmt.push(['_trackEvent', '上传页', 'click', '点击立即预测'])
      if (this.dialogText) {
        this.visible = true
      } else if (ziping) {
        clicked = true
      } else if (!this.photo) {
        this.toast('请上传照片')
      } else if (!this.faceId) {
        clicked = true
      } else {
        this.$router.replace({
          name: 'loading',
          query: {
            index: this.index
          }
        })
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
  .upload-page {
    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    overflow: hidden;
    height:100%;
    // background: {
    //     image: url(~@/assets/image/bg.png);
    //     size: 100%;
    //     repeat: no-repeat;
    // };
    .upload-bg {
      position: absolute;
      left: 0;
      width: 100%;
      top: 0;
    }
    .uploader-wrap {
      position: absolute;
      top:50px;
      width: 750px;
      height: 1009px;
      z-index: 10;
      background: {
        // image: url(~@/assets/image/upload-bg.png);
        size: cover;
        position: center;
      };
      .uploader-label {
        position: absolute;
        width: 536px;
        height: 714px;
        top: 120px;
        left: 106px;
        background: {
            size: cover;
            position: center;
            repeat: no-repeat;
        }
        &.has-photo {
          &:after {
            display: none;
          }
        }
      }
      .uploader-input {
        display: none;
      }
    }
    .submit-wrap{
      position: absolute;
      left: 140px;
      top: 920px;
      width: 480px;
      height: 150px;
      z-index: 10;
    }
    .toast {
      position: fixed;
      top: 60%;
      left: 50%;
      z-index: 999;
      transform: translate(-50%, -50%);
      background-color: rgba(0, 0, 0, 0.5);
      text-align: center;
      font-size: 26px;
      line-height: 1;
      padding: 24px;
      color: #ffffff;
      -webkit-border-radius: 15px;
      -moz-border-radius: 15px;
      border-radius: 15px;
    }
  }
</style>
